package com.sgai.zero_robot.ui.select_file_config;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.documentfile.provider.DocumentFile;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.sgai.zero_robot.base.BaseActivity;
import com.sgai.zero_robot.base.BaseAdapter;
import com.sgai.zero_robot.base.BaseViewModel;
import com.sgai.zero_robot.databinding.ActivitySelectFileConfigBinding;
import com.sgai.zero_robot.ui.history.RunnableCallBack;
import com.sgai.zero_robot.utils.LogUtil;
import com.sgai.zero_robot.utils.ThreadPoolUtils;
import java.util.List;

public class SelectFileConfigActivity extends BaseActivity<ActivitySelectFileConfigBinding, BaseViewModel> implements View.OnClickListener {
    private SelectFileListAdapter selectFileListAdapter ;
    private TowerDetail towerDetail;
    @Override
    public void initViews(Bundle savedInstanceState) {
        mBinding.tvCancel.setOnClickListener(this);
        mBinding.tvConfirm.setOnClickListener(this);
        selectFileListAdapter = new SelectFileListAdapter(this);
        mBinding.rvTest.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvTest.setAdapter(selectFileListAdapter);
        selectFileListAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<TowerDetail>() {
            @Override
            public void onItemClick(int position, TowerDetail towerDetail) {
                int currentIndex = selectFileListAdapter.getCurrentIndex();
                if (currentIndex == position) {
                    return;
                }
                SelectFileConfigActivity.this.towerDetail=towerDetail;
                selectFileListAdapter.setCurrentIndex(position);
                selectFileListAdapter.notifyItemChanged(currentIndex);
                selectFileListAdapter.notifyItemChanged(position);
            }
        });
        if (ContextCompat.checkSelfPermission(SelectFileConfigActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(SelectFileConfigActivity.this, "申请权限", Toast.LENGTH_SHORT).show();
            // 申请 相机 麦克风权限
            ActivityCompat.requestPermissions(SelectFileConfigActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 102);
        } else {
           startSelectFile();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 102){
            if (ContextCompat.checkSelfPermission(SelectFileConfigActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(SelectFileConfigActivity.this, "请手动开启文件读写权限", Toast.LENGTH_SHORT).show();
            }else{
                startSelectFile();
            }
        }
    }

    private void startSelectFile(){
        String[] mimeTypes = new String[]{
                "text/csv",
                "application/vnd.ms-excel", // .xls
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" // .xlsx
        };
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*"); // 使用 EXTRA_MIME_TYPES 指定
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK || data == null) {
            finish();
            return;
        }
        Uri uri = data.getData();
        if (uri == null){
            finish();
            return;
        };
        if (requestCode == 101){
            // 通过 MIME 或文件名后缀判断
            String mime = getContentResolver().getType(uri);
            String name = queryName(uri);
            LogUtil.i(TAG, "Picked file: " + name + " mime: " + mime);

            if (name != null && (name.toLowerCase().endsWith(".xlsx") || name.toLowerCase().endsWith(".xls"))
                    || (mime != null && (mime.contains("excel") || mime.contains("spreadsheet")))) {
                showLoading("正在加载...");
                readXLSRunnable = new ReadXLSRunnable(this, uri, new RunnableCallBack<List<TowerDetail>>() {
                    @Override
                    public void onResult(List<TowerDetail> towerDetails) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoading();
                                if (towerDetails == null||towerDetails.size()<=0){
                                    showToast("未解析到数据");
                                    return;
                                }
                                selectFileListAdapter.setData(towerDetails);
                            }
                        });
                    }
                });
                ThreadPoolUtils.getInstance().addParallelTask(readXLSRunnable);
            } else {
                showToast("文件类型错误，请检查");
            }
        }
    }

    private ReadXLSRunnable readXLSRunnable;
    // 辅助：从 Uri 查询文件名（简单实现）
    private String queryName(Uri uri) {
        String result = null;
        try {
            DocumentFile doc = DocumentFile.fromSingleUri(this, uri);
            if (doc != null) result = doc.getName();
        } catch (Exception e) {
            LogUtil.e(e,Thread.currentThread());
        }
        return result;
    }
    @Override
    public void loadData() {

    }
    @Override
    public void onClick(View v) {
        if ( mBinding.tvCancel == v){
            setResult(RESULT_CANCELED);
            finish();
        }else if (mBinding.tvConfirm == v){
            if (towerDetail == null){
                showToast("请选择杆塔！！！");
            }
            Intent intent = new Intent();
            intent.putExtra("province",towerDetail.getProvince());
            intent.putExtra("city",towerDetail.getCity());
            intent.putExtra("lineName",towerDetail.getLineName());
            intent.putExtra("towerNum",towerDetail.getTowerNum());
            setResult(RESULT_OK,intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (readXLSRunnable!=null){
            ThreadPoolUtils.getInstance().removeParallelTask(readXLSRunnable);
        }
    }
}